import time
import os
import re
import json
import requests
import hashlib
from datetime import datetime, timedelta

def download_image(url: str, local_name: str) -> str:
    """
    下载网络上的图片并重命名

    :param url: 图片的网络 URL
    :param local_name: 本地保存的文件名（包含路径）
    :return: 下载成功返回文件路径，失败返回错误信息
    """
    try:
        # 确保目标目录存在
        os.makedirs(os.path.dirname(local_name), exist_ok=True)

        # 请求图片数据
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 将图片写入文件
        with open(local_name, 'wb') as file:
            for chunk in response.iter_content(1024):
                file.write(chunk)

        return local_name
    except requests.exceptions.RequestException as e:
        return f"网络请求错误：{e}"
    except Exception as e:
        return f"发生错误：{e}"
    
def get_token():
    url = "http://172.18.172.177:4000/api/oauth/login"
    params = {
        "username": "admin",
        "password": "kans2023"
    }
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Connection": "keep-alive",
        "Origin": "http://rpa.chicmax.net:3000",
        "Referer": "http://rpa.chicmax.net:3000/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
    }
    # 发送 POST 请求
    response = requests.post(url, params=params, headers=headers, verify=False)
    # 输出响应内容
    if response.status_code != 200:
        raise Exception("获取token失败")
    return response.json()["data"]["token"]


#获取手机验证码
def show_input_dialog(phone):
    try:
        url = "http://172.18.172.177:4000/api/settingsys/GetSendLogs"
        token = get_token()
        params = {
            "query": phone,
            "page": 1,
            "pagesize": 1
        }
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Authorization": "bearer " + token,
            "Connection": "keep-alive",
            "Origin": "http://rpa.chicmax.net:3000",
            "Referer": "http://rpa.chicmax.net:3000/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
        }

        # 发送 GET 请求
        response = requests.get(url, params=params, headers=headers)
        # 输出响应内容
        if response.status_code != 200:
            raise Exception("获取验证码失败")
        message = response.json()["data"]["items"][0]["messageContent"]
        pattern = r'您的验证码是: (\d+)'
        # 使用re.search()查找匹配项
        match = re.search(pattern, message)
        # 如果找到匹配项，则提取验证码
        if match:
            verification_code = match.group(1)
            return verification_code
        else:
            raise Exception(f"验证码解析失败,字符串为：{message}")
    except Exception as e:
        raise Exception(f"验证码获取解析失败")



def gen_date(timestamp=None, format='%Y-%m-%d %H:%M:%S') -> str:
    '''
    生成人类喜好的时间格式

    如果时间戳为空，生成当前时间
    :param timestamp:
    :return:
    '''
    if timestamp:
        time_local = time.localtime(timestamp)
    else:
        time_local = time.localtime(int(time.time()))
    return time.strftime(format, time_local)
    


def parse_relative_time(time_str):
    # 检查是否是月份-日期格式（MM-DD）
    month_day_pattern = re.compile(r'^(\d{2})-(\d{2})$')
    match = month_day_pattern.match(time_str)
    if match:
        month, day = map(int, match.groups())
        current_year = datetime.now().year
        # 构造日期对象
        full_date = datetime(current_year, month, day)
        return full_date.strftime("%Y-%m-%d")

    # 检查是否是相对时间格式（今天、昨天、X天前）
    if time_str.startswith("今天"):
        parts = time_str.split()
        time_of_day = parts[1] if len(parts) > 1 else ""
        now = datetime.now()
        full_time = now.replace(hour=int(time_of_day[:2]), minute=int(time_of_day[3:]))
    elif time_str.startswith("昨天"):
        parts = time_str.split()
        time_of_day = parts[1] if len(parts) > 1 else ""
        now = datetime.now()
        full_time = now - timedelta(days=1)
        full_time = full_time.replace(hour=int(time_of_day[:2]), minute=int(time_of_day[3:]))
    elif "天前" in time_str:
        days_ago_str = time_str[:-2]  # 去掉"天前"
        days_ago = int(days_ago_str)
        now = datetime.now()
        full_time = now - timedelta(days=days_ago)
        # 这里我们没有指定时间，所以默认设置为00:00
    else:
        # 如果都不是，直接返回原始字符串（或者可以抛出一个异常）
        return time_str

    return full_time.strftime("%Y-%m-%d %H:%M")


def get_internet_ip()->str:
    response = requests.get('https://httpbin.org/ip')
    response_json = json.loads(response.text)
    return response_json['origin']



def parse_xhs_post_relative_time(time_str):
    now = datetime.now()

    # 提取地区信息，但排除时间格式
    region = ""
    # 修改正则表达式，排除时间格式 HH:MM
    region_match = re.search(r'\s+(?!\d{1,2}:\d{2})([^\s]+?(?:地区|省|市|自治区)?)$', time_str)
    if region_match:
        region = region_match.group(1)

    # 清理字符串，移除多余的地区信息和"编辑于"等前缀
    time_str = re.sub(r'(编辑于\s*)|(\s+(?!\d{1,2}:\d{2})[^\s]+?(?:地区|省|市|自治区)?$)', '', time_str.strip())

    # 处理 MM-DD 格式
    if re.match(r'^\d{2}-\d{2}$', time_str):
        try:
            month, day = map(int, time_str.split('-'))
            return now.replace(month=month, day=day).strftime("%Y-%m-%d"), region
        except ValueError:
            return time_str, region

    # 处理完整的 YYYY-MM-DD 格式
    if re.match(r'^\d{4}-\d{2}-\d{2}', time_str):
        return time_str, region

    # 处理"天前"格式
    days_ago_match = re.match(r'^(\d+)\s*天前', time_str)
    if days_ago_match:
        days = int(days_ago_match.group(1))
        result_date = now - timedelta(days=days)
        return result_date.strftime("%Y-%m-%d"), region

    # 处理"刚刚"的情况
    if time_str.strip() == "刚刚":
        return now.strftime("%Y-%m-%d %H:%M"), region

    # 处理今天、昨天、前天格式
    time_parts = time_str.split()
    relative_day = time_parts[0]
    time_of_day = time_parts[1] if len(time_parts) > 1 else "00:00"

    days_map = {
        "今天": 0,
        "昨天": 1,
        "前天": 2
    }

    if relative_day in days_map:
        result_date = now - timedelta(days=days_map[relative_day])
        if ":" in time_of_day:
            hour, minute = map(int, time_of_day.split(":"))
            result_date = result_date.replace(hour=hour, minute=minute)
        return result_date.strftime("%Y-%m-%d %H:%M"), region

    # 如果无法解析，返回原始字符串
    return time_str, region

def simple_md5(st):
    md5 = hashlib.md5()
    md5.update(st.encode('utf-8'))
    return md5.hexdigest()


def pre_n_days(n: int) -> str:
    return gen_date(time.time() - n * 24 * 60 * 60).split(' ')[0]

if __name__ == "__main__":
    print(pre_n_days(0))
    # print(parse_relative_time("02-01"))
    # print(parse_relative_time("今天 01:05"))
    # print(parse_relative_time("01-29 欧洲地区")[0])
    # print(parse_relative_time("1231231"))
    # print(parse_relative_time( "编辑于 2020-01-29 上海"))